package dk.com.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import dk.com.constan.Site;

public class HttpClientUtil {

	private DefaultHttpClient client;
	private HttpContext localContext;
	private CookieStore cookiestore;

	// Constructor
	public HttpClientUtil() {
		client = new DefaultHttpClient();
		localContext = new BasicHttpContext();
		cookiestore = new BasicCookieStore();
		client.getParams()
				.setParameter("http.useragent",
						"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0");
		client.getParams().setParameter("http.protocol.handle-redirects", true);
		client.getParams().setParameter("http.protocol.max-redirects", 1)
				.setParameter("Host", "www.amway2u.com");
	}

	// Make a get request to a page
	public String getPage(String url) {
		HttpGet request;
		HttpResponse response;
		HttpEntity entity;
		String content = "";
		try {
			request = new HttpGet(url);
			System.out.println("Fetching " + url);
			response = client.execute(request, localContext);
			entity = response.getEntity();
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	@SuppressWarnings("deprecation")
	public String loginToAmway(String username, String password) {
		HttpPost httpost = new HttpPost(Site.AMWAY_LOGIN);
		HttpResponse response;
		HttpEntity entity;
		try {
			String html = getPage(Site.AMWAY_HOME);
			List<BasicNameValuePair> nvps = getFormElements(html , username,
					password);
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			response = client.execute(httpost, localContext);
			entity = response.getEntity();

			List<?> cookies = client.getCookieStore().getCookies();
			cookies = client.getCookieStore().getCookies();
			if (cookies.isEmpty()) {
				System.out.println("None");
			} else {
				for (int i = 0; i < cookies.size(); i++) {
					System.out.println("- " + cookies.get(i).toString());
				}
			}
			return EntityUtils.toString(entity);

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public List<BasicNameValuePair> getFormElements(String html,
			String username, String password) {
		org.jsoup.nodes.Document doc = Jsoup.parse(html);
		Element loginform = doc.getElementsByAttributeValue("name", "frmLogin")
				.first();
		Elements inputElements = loginform.getElementsByTag("input");
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		for (Element inputElement : inputElements) {
			String key = inputElement.attr("name");
			String value = inputElement.attr("value");
			// System.out.println(key+" : " + value);
			if (key.equals("adano"))
				value = username;
			else if (key.equals("adapass"))
				value = password;
			else if (key.equals("PersistentCookie"))
				value = "no";
			nvps.add(new BasicNameValuePair(key, value));
		}
		System.out.println(nvps.toString());
		return nvps;
	}

	// Dispose the client
	@SuppressWarnings("deprecation")
	public void close() {
		client.getConnectionManager().shutdown();
	}
}